﻿using FlickrNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WindowsLive.Writer.Api;

namespace TrailImage {
    public static class Security {
		/// <summary>
		/// Verify that profile is authenticated
		/// </summary>
		/// <returns>Boolean indicating success</returns>
		internal static bool Verify(IWin32Window liveWriterWindow)
		{
			FlickrNet.Auth authorization = null;

			if (!Profile.Current.IsEmptyToken)
			{
				// validate existing token
				using (WaitForm form = new WaitForm())
				{
					// prepare form
					form.Label = "Verifying Authentication …";
					form.DoWork += (sender, e) => {
						try
						{
							authorization = FlickrPlugin.Flickr.AuthOAuthCheckToken();
						}
						catch (Exception ex)
						{
							authorization = null;
						}

						if (authorization == null)
						{
							Profile.Current.Token = null;
							FlickrPlugin.Flickr.OAuthAccessToken = null;							
						}
						else
						{
							Profile.Current.Token = authorization.Token;
						}
					};
					// show form
					if (form.ShowDialog(liveWriterWindow) != DialogResult.OK) { return false; }
				}
			}

			if (Profile.Current.IsEmptyToken)
			{
				// if no token then begin the authentication process
				Security.Authenticate(liveWriterWindow);
			}
			return (!Profile.Current.IsEmptyToken);
		}

		public static bool Authenticate(IWin32Window liveWriterWindow)
		{
            using (AuthForm form = new AuthForm())
			{
				return (form.ShowDialog(liveWriterWindow) == DialogResult.OK);
            }
        }
    }
}
